package network2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {

    private DatagramSocket socket = null;

    public UdpEchoServer(int Port) throws SocketException {
        socket = new DatagramSocket(Port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true) {
            //  从客户端接收请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //  计算响应
            String respond = process(request);
            //  回复响应给客户端
            DatagramPacket respondPacket = new DatagramPacket(respond.getBytes(),respond.getBytes().length,requestPacket.getSocketAddress());
            socket.send(respondPacket);
            System.out.printf("[%s:%d] req: %s, resp:%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(), request, respond);
        }

    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9091);
        udpEchoServer.start();
    }
}
